<template>
	<view class="recipes-container">
		<view class="header">
			<view class="back-btn" @tap="goBack">
				<text class="iconfont icon-back"></text>
			</view>
			<view class="title" @click="handleTitleClick">健康食谱</view>
			<view class="add-btn" @tap="goToAddRecipe">
				<text class="iconfont icon-add"></text>
			</view>
		</view>
		
		<!-- 类型筛选 -->
		<view class="type-filter">
			<view 
				class="filter-item" 
				:class="{ active: recipeType === 'all' }"
				@tap="selectType('all')"
			>
				全部
			</view>
			<view 
				class="filter-item" 
				:class="{ active: recipeType === 'breakfast' }"
				@tap="selectType('breakfast')"
			>
				早餐
			</view>
			<view 
				class="filter-item" 
				:class="{ active: recipeType === 'lunch' }"
				@tap="selectType('lunch')"
			>
				午餐
			</view>
			<view 
				class="filter-item" 
				:class="{ active: recipeType === 'dinner' }"
				@tap="selectType('dinner')"
			>
				晚餐
			</view>
			<view 
				class="filter-item" 
				:class="{ active: recipeType === 'snack' }"
				@tap="selectType('snack')"
			>
				小食
			</view>
		</view>
		
		<!-- 食谱列表 -->
		<view class="recipes-list">
			<view 
				class="recipe-item" 
				v-for="(item, index) in filteredRecipes" 
				:key="index"
				@tap="viewRecipeDetail(item)"
			>
				<image :src="item.image || '/static/images/placeholder.png'" mode="aspectFill" class="recipe-image"></image>
				<view class="recipe-tag" :class="item.type">{{getTypeText(item.type)}}</view>
				<view class="recipe-info">
					<view class="recipe-name">{{item.name}}</view>
					<view class="recipe-desc">{{item.desc}}</view>
					<view class="recipe-nutrition">
						<text class="nutrition-item">{{item.calories}}kcal</text>
						<text class="nutrition-item">碳水{{item.carbs}}g</text>
						<text class="nutrition-item">蛋白质{{item.protein}}g</text>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 空状态 -->
		<view class="empty-state" v-if="filteredRecipes.length === 0 && !isLoading">
			<image src="/static/images/no-data.png" mode="aspectFit" class="empty-image"></image>
			<view class="empty-text">暂无相关食谱</view>
			<view class="empty-tips">{{emptyTips}}</view>
			<button class="refresh-btn" @tap="loadRecipes">重新加载</button>
		</view>
		
		<!-- 调试信息 -->
		<view class="debug-info" v-if="showDebug">
			<view class="debug-title">调试信息</view>
			<view class="debug-content">
				<view>API响应码: {{apiResponseCode}}</view>
				<view>API消息: {{apiResponseMsg}}</view>
				<view>食谱数量: {{recipesList.length}}</view>
				<view>当前筛选: {{recipeType}}</view>
				<view>筛选后数量: {{filteredRecipes.length}}</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import { ref, computed, onMounted } from 'vue'
	import { getAllRecipes } from '@/common/api/diet.js'
	
	// 调试模式
	const showDebug = ref(false)
	// API响应信息
	const apiResponseCode = ref(null)
	const apiResponseMsg = ref('')
	// 加载状态
	const isLoading = ref(false)
	// 空状态提示
	const emptyTips = ref('请尝试其他筛选条件')
	
	// 食谱类型：all(全部), breakfast(早餐), lunch(午餐), dinner(晚餐), snack(小食)
	const recipeType = ref('all')
	// 食谱列表
	const recipesList = ref([])
	
	// 根据类型筛选食谱
	const filteredRecipes = computed(() => {
		if (recipeType.value === 'all') {
			return recipesList.value
		} else {
			return recipesList.value.filter(item => item.type === recipeType.value)
		}
	})
	
	// 获取类型文本
	const getTypeText = (type) => {
		const typeMap = {
			'breakfast': '早餐',
			'lunch': '午餐',
			'dinner': '晚餐',
			'snack': '小食'
		}
		return typeMap[type] || '全部'
	}
	
	// 页面加载时获取数据
	onMounted(() => {
		loadRecipes()
	})
	
	// 加载食谱列表
	const loadRecipes = async () => {
		try {
			isLoading.value = true
			emptyTips.value = '请尝试其他筛选条件'
			
			uni.showLoading({
				title: '加载中...'
			})
			
			console.log('开始请求食谱列表')
			const res = await getAllRecipes()
			
			// 保存API响应信息
			apiResponseCode.value = res.code
			apiResponseMsg.value = res.msg || ''
			
			console.log('食谱列表API响应:', JSON.stringify(res).substring(0, 200))
			
			if (res.code === 0) {
				// 处理后端返回的数据结构
				if (res.data && res.data.list) {
					// 如果返回的是分页数据结构
					recipesList.value = res.data.list.map(item => ({
						id: item.id,
						name: item.title || item.name,
						image: item.image || '/static/images/placeholder.png',
						desc: item.description || item.desc || '',
						calories: item.calories || 0,
						carbs: item.carbs || 0,
						protein: item.protein || 0,
						fat: item.fat || 0,
						type: item.mealType || 'breakfast'
					}))
				} else if (Array.isArray(res.data)) {
					// 如果直接返回数组
					recipesList.value = res.data.map(item => ({
						id: item.id,
						name: item.title || item.name,
						image: item.image || '/static/images/placeholder.png',
						desc: item.description || item.desc || '',
						calories: item.calories || 0,
						carbs: item.carbs || 0,
						protein: item.protein || 0,
						fat: item.fat || 0,
						type: item.mealType || 'breakfast'
					}))
				} else {
					console.error('食谱列表数据格式不正确')
					emptyTips.value = '数据格式不正确，请重试'
					recipesList.value = []
				}
				
				// 检查是否有数据
				if (recipesList.value.length === 0) {
					console.log('食谱列表为空')
					emptyTips.value = '暂无食谱数据'
				}
				
				// 检查图片URL
				recipesList.value.forEach(item => {
					if (item.image) {
						checkImageUrl(item)
					}
				})
			} else {
				console.error('获取食谱列表失败:', res.msg)
				emptyTips.value = '获取数据失败，请重试'
				uni.showToast({
					title: res.msg || '加载失败',
					icon: 'none'
				})
			}
		} catch (e) {
			console.error('加载食谱异常:', e)
			emptyTips.value = '网络错误，请重试'
			uni.showToast({
				title: '加载失败',
				icon: 'none'
			})
		} finally {
			isLoading.value = false
			uni.hideLoading()
		}
	}
	
	// 检查图片URL是否有效
	const checkImageUrl = (item) => {
		if (!item.image) return
		
		uni.getImageInfo({
			src: item.image,
			success: () => {
				console.log('图片URL有效:', item.image)
			},
			fail: () => {
				console.error('图片URL无效:', item.image)
				// 如果图片无效，使用默认图片
				item.image = '/static/images/placeholder.png'
			}
		})
	}
	
	// 选择食谱类型
	const selectType = (type) => {
		recipeType.value = type
	}
	
	// 查看食谱详情
	const viewRecipeDetail = (recipe) => {
		// 保存ID到全局变量
		getApp().globalData = getApp().globalData || {}
		getApp().globalData.recipeParams = {
			id: recipe.id
		}
		console.log('跳转到食谱详情，ID:', recipe.id)
		
		// 跳转到详情页
		uni.navigateTo({
			url: `/pages/diet/recipe?id=${recipe.id}`,
			fail: (err) => {
				console.error('跳转失败:', err)
				uni.showToast({
					title: '页面跳转失败',
					icon: 'none'
				})
			}
		})
	}
	
	// 返回上一页
	const goBack = () => {
		uni.navigateBack()
	}
	
	// 跳转到添加食谱页面
	const goToAddRecipe = () => {
		uni.navigateTo({
			url: '/pages/diet/add-recipe'
		})
	}
	
	// 处理标题点击事件
	const handleTitleClick = () => {
		// 简单的计数器实现
		const now = Date.now()
		// 使用全局变量存储状态
		getApp().globalData = getApp().globalData || {}
		getApp().globalData.lastTitleClickTime = getApp().globalData.lastTitleClickTime || 0
		getApp().globalData.titleClickCount = getApp().globalData.titleClickCount || 0
		
		if (now - getApp().globalData.lastTitleClickTime < 500) {
			getApp().globalData.titleClickCount++
			if (getApp().globalData.titleClickCount >= 5) {
				showDebug.value = !showDebug.value
				uni.showToast({
					title: showDebug.value ? '调试模式已开启' : '调试模式已关闭',
					icon: 'none'
				})
				getApp().globalData.titleClickCount = 0
			}
		} else {
			getApp().globalData.titleClickCount = 1
		}
		getApp().globalData.lastTitleClickTime = now
	}
</script>

<style lang="scss">
	.recipes-container {
		min-height: 100vh;
		background-color: #f5f7fa;
		padding-bottom: 30rpx;
		
		.header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 20rpx;
			background-color: #fff;
			position: sticky;
			top: 0;
			z-index: 100;
			
			.back-btn {
				width: 60rpx;
				height: 60rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				
				.icon-back {
					font-size: 36rpx;
					color: #333;
				}
			}
			
			.title {
				font-size: 32rpx;
				font-weight: bold;
				color: #333;
			}
			
			.add-btn {
				width: 60rpx;
				height: 60rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				
				.icon-add {
					font-size: 36rpx;
					color: #333;
				}
			}
		}
		
		.type-filter {
			display: flex;
			background-color: #fff;
			margin-bottom: 20rpx;
			overflow-x: auto;
			white-space: nowrap;
			
			.filter-item {
				padding: 20rpx 30rpx;
				font-size: 28rpx;
				color: #666;
				position: relative;
				
				&.active {
					color: #8cc9a1;
					font-weight: bold;
					
					&::after {
						content: '';
						position: absolute;
						bottom: 0;
						left: 50%;
						transform: translateX(-50%);
						width: 40rpx;
						height: 4rpx;
						background-color: #8cc9a1;
						border-radius: 2rpx;
					}
				}
			}
		}
		
		.recipes-list {
			padding: 0 20rpx;
			display: flex;
			flex-wrap: wrap;
			justify-content: space-between;
			
			.recipe-item {
				width: 48%;
				background-color: #fff;
				border-radius: 12rpx;
				margin-bottom: 20rpx;
				overflow: hidden;
				position: relative;
				
				.recipe-image {
					width: 100%;
					height: 200rpx;
					background-color: #f0f0f0;
				}
				
				.recipe-tag {
					position: absolute;
					top: 20rpx;
					left: 0;
					padding: 6rpx 16rpx;
					font-size: 22rpx;
					color: #fff;
					border-radius: 0 20rpx 20rpx 0;
					
					&.breakfast {
						background-color: #f0ad4e;
					}
					
					&.lunch {
						background-color: #5bc0de;
					}
					
					&.dinner {
						background-color: #d9534f;
					}
					
					&.snack {
						background-color: #8cc9a1;
					}
				}
				
				.recipe-info {
					padding: 15rpx;
					
					.recipe-name {
						font-size: 28rpx;
						font-weight: bold;
						color: #333;
						margin-bottom: 10rpx;
						white-space: nowrap;
						overflow: hidden;
						text-overflow: ellipsis;
					}
					
					.recipe-desc {
						font-size: 24rpx;
						color: #666;
						margin-bottom: 10rpx;
						display: -webkit-box;
						-webkit-box-orient: vertical;
						-webkit-line-clamp: 2;
						overflow: hidden;
						height: 72rpx;
					}
					
					.recipe-nutrition {
						display: flex;
						flex-wrap: wrap;
						
						.nutrition-item {
							font-size: 22rpx;
							color: #999;
							margin-right: 15rpx;
							margin-bottom: 5rpx;
							
							&:last-child {
								margin-right: 0;
							}
						}
					}
				}
			}
		}
		
		.empty-state {
			display: flex;
			flex-direction: column;
			align-items: center;
			padding: 100rpx 0;
			
			.empty-image {
				width: 200rpx;
				height: 200rpx;
				margin-bottom: 30rpx;
			}
			
			.empty-text {
				font-size: 32rpx;
				color: #333;
				margin-bottom: 10rpx;
			}
			
			.empty-tips {
				font-size: 24rpx;
				color: #999;
				margin-bottom: 30rpx;
			}
			
			.refresh-btn {
				width: 240rpx;
				height: 70rpx;
				background-color: #8cc9a1;
				color: #fff;
				font-size: 28rpx;
				border-radius: 35rpx;
				display: flex;
				align-items: center;
				justify-content: center;
			}
		}
		
		.debug-info {
			padding: 20rpx;
			background-color: #fff;
			border-radius: 12rpx;
			margin-top: 20rpx;
			
			.debug-title {
				font-size: 28rpx;
				font-weight: bold;
				color: #333;
				margin-bottom: 10rpx;
			}
			
			.debug-content {
				font-size: 24rpx;
				color: #666;
			}
		}
	}
</style> 